/**
 * Created by yeanzhi on 15/7/1.
 */
var nodemailer = require('nodemailer');
var db = require('./db');
var co = require('co'),
	request = require('request'),
	schedule = require("node-schedule"),
	cheerio = require('cheerio'),
	db = require('./db');
var email = require("emailjs/email");
var server = email.server.connect({
	user: "a1308118099@163.com",
	password: "s807754634",
	host: "smtp.163.com",
	ssl: true
});

var sendemail = function (title, link, id) {
	db.subscriber.findAll({
		where: {
			status: 1
		},
		attributes: ['email']
	}).then(function (projects) {
		var sendEmailStr = "";
		for (var i = 0, l = projects.length; i < l; i++) {
			sendEmailStr += projects[i].get('email') + ",";
		}
		sendEmailStr = sendEmailStr.substr(0, sendEmailStr.length - 1);

		server.send({
			text: title,
			from: "学生周知 <a1308118099@163.com>",
			to: sendEmailStr,
			subject: title,
			attachment: [
				{
					data: '<html><body><a href="http://ssdut.dlut.edu.cn' + link + '"><p>' + title + '</p></a></body> </html>',
					alternative: true
				}
			]
		}, function (err, message) {
			if (err) {
				return console.log(error);
			} else {
				db.zhouzhi.find({
					where: {
						id: id
					}
				}).then(function (p) {
					p.sub_send_email = 0;
					p.save().then(function (p) {
					});
				});
			}
		});
	});
};

var rule = new schedule.RecurrenceRule();
var times = [];
for (var i = 1; i < 60; i++) {
	if (i % 2 == 0) {
		times.push(i);
	}
}
rule.minute = times;
var j = schedule.scheduleJob(rule, function () {
	db.zhouzhi.findAll({
		where: {
			sub_send_email: 1
		}
	}).then(function (p) {
		var len = p.length;
		for (var i = 0; i < len; i++) {
			(function (i) {
				sendemail(p[i].title, p[i].link, p[i].id);
			}(i))
		}
	});
});
